import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Tag, Button, Descriptions, message, Spin, Divider } from 'antd';
import { ArrowLeftOutlined, ReloadOutlined, LineChartOutlined } from '@ant-design/icons';
import { stockApi, StockModel } from '../services/stockApi';

const StockDetail = ({ stock, onBack }) => {
  const [stockDetail, setStockDetail] = useState(null);
  const [loading, setLoading] = useState(false);

  // 加载股票详情
  const loadStockDetail = async () => {
    if (!stock) return;
    
    setLoading(true);
    try {
      const data = await stockApi.getStockByCode(stock.no);
      setStockDetail(data);
      message.success('股票详情加载成功');
    } catch (error) {
      console.error('加载股票详情失败:', error);
      message.error('加载股票详情失败');
      setStockDetail(stock); // 使用列表中的基础信息
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (stock) {
      loadStockDetail();
    }
  }, [stock]);

  if (!stock) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <p>请先选择一只股票查看详情</p>
          <Button type="primary" onClick={onBack}>
            返回股票列表
          </Button>
        </div>
      </Card>
    );
  }

  const currentStock = stockDetail || stock;
  const change = StockModel.calculateChangeRate(currentStock.close_price, currentStock.open_price);

  return (
    <Card
      title={
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={onBack}
            style={{ marginRight: 16 }}
          >
            返回
          </Button>
          <span>股票详情</span>
        </div>
      }
      extra={
        <Button 
          icon={<ReloadOutlined />} 
          onClick={loadStockDetail}
          loading={loading}
        >
          刷新
        </Button>
      }
    >
      <Spin spinning={loading}>
        {/* 基本信息头部 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col span={24}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
              <Tag color={currentStock.market === 'SH' ? '#f50' : '#2db7f5'} size="large">
                {currentStock.market}
              </Tag>
              <h1 style={{ margin: 0, marginLeft: 8 }}>
                {currentStock.no}
                <span style={{ fontSize: '16px', color: '#666', marginLeft: 8 }}>
                  {currentStock.market === 'SH' ? '上证' : '深证'}股票
                </span>
              </h1>
            </div>
          </Col>
        </Row>

        {/* 价格统计信息 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="当前价格"
                value={currentStock.close_price || 0}
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#3f8600' }}
                suffix={
                  <Tag color={change.isPositive ? 'red' : 'green'}>
                    {change.isPositive ? '+' : '-'}{change.rate}%
                  </Tag>
                }
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="开盘价"
                value={currentStock.open_price || 0}
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#cf1322' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="最高价"
                value={currentStock.max_price || 0}
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#cf1322' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="最低价"
                value={currentStock.min_price || 0}
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#3f8600' }}
              />
            </Card>
          </Col>
        </Row>

        <Divider />

        {/* 详细信息 */}
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Card title="详细信息" extra={<LineChartOutlined />}>
              <Descriptions bordered column={{ xs: 1, sm: 2, md: 3 }}>
                <Descriptions.Item label="股票代码">
                  {currentStock.no}
                </Descriptions.Item>
                <Descriptions.Item label="市场">
                  <Tag color={currentStock.market === 'SH' ? '#f50' : '#2db7f5'}>
                    {currentStock.market}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="股票内部ID">
                  {currentStock.sid}
                </Descriptions.Item>
                
                <Descriptions.Item label="总股本">
                  {StockModel.formatShares(currentStock.total_share)}
                </Descriptions.Item>
                <Descriptions.Item label="流通股本">
                  {StockModel.formatShares(currentStock.liqa_share)}
                </Descriptions.Item>
                <Descriptions.Item label="流通比例">
                  {currentStock.total_share && currentStock.liqa_share 
                    ? `${((currentStock.liqa_share / currentStock.total_share) * 100).toFixed(2)}%`
                    : '--'
                  }
                </Descriptions.Item>
                
                <Descriptions.Item label="年份">
                  {currentStock.year}
                </Descriptions.Item>
                <Descriptions.Item label="股息">
                  {currentStock.dividend ? `¥${currentStock.dividend.toFixed(2)}` : '--'}
                </Descriptions.Item>
                <Descriptions.Item label="涨跌幅">
                  <span style={{ 
                    color: change.isPositive ? '#ff4d4f' : '#52c41a',
                    fontWeight: 'bold'
                  }}>
                    {change.isPositive ? '+' : '-'}{change.rate}%
                  </span>
                </Descriptions.Item>
                
                <Descriptions.Item label="价格区间" span={3}>
                  {StockModel.formatPrice(currentStock.min_price)} - {StockModel.formatPrice(currentStock.max_price)}
                </Descriptions.Item>
                
                <Descriptions.Item label="股票全称" span={3}>
                  {currentStock.market === 'SH' ? '上海证券交易所' : '深圳证券交易所'} {currentStock.no}
                </Descriptions.Item>
              </Descriptions>
            </Card>
          </Col>
        </Row>

        {/* 价格走势分析 */}
        <Row gutter={[16, 16]} style={{ marginTop: 24 }}>
          <Col span={24}>
            <Card title="价格分析">
              <Row gutter={[16, 16]}>
                <Col xs={24} sm={12} md={8}>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: '14px', color: '#666', marginBottom: 8 }}>
                      价格波动
                    </div>
                    <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#1890ff' }}>
                      {currentStock.max_price && currentStock.min_price 
                        ? `¥${(currentStock.max_price - currentStock.min_price).toFixed(2)}`
                        : '--'
                      }
                    </div>
                  </div>
                </Col>
                <Col xs={24} sm={12} md={8}>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: '14px', color: '#666', marginBottom: 8 }}>
                      振幅
                    </div>
                    <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#faad14' }}>
                      {currentStock.max_price && currentStock.min_price && currentStock.open_price
                        ? `${(((currentStock.max_price - currentStock.min_price) / currentStock.open_price) * 100).toFixed(2)}%`
                        : '--'
                      }
                    </div>
                  </div>
                </Col>
                <Col xs={24} sm={12} md={8}>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: '14px', color: '#666', marginBottom: 8 }}>
                      涨跌金额
                    </div>
                    <div style={{ 
                      fontSize: '18px', 
                      fontWeight: 'bold', 
                      color: change.isPositive ? '#ff4d4f' : '#52c41a'
                    }}>
                      {currentStock.close_price && currentStock.open_price
                        ? `¥${Math.abs(currentStock.close_price - currentStock.open_price).toFixed(2)}`
                        : '--'
                      }
                    </div>
                  </div>
                </Col>
              </Row>
            </Card>
          </Col>
        </Row>
      </Spin>
    </Card>
  );
};

export default StockDetail;